package com.applcn.user.async;

import com.applcn.user.threadlocal.UserRequestContext;
import com.applcn.user.threadlocal.UserRequestContextHolder;
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 切换线程时 传递 请求上下文信息
 * 请求上下文信息 org.springframework.web.context.request.RequestContextHolder
 * https://stackoverflow.com/questions/23732089/how-to-enable-request-scope-in-async-task-executor
 *
 * @author st
 */
public class ContextCopyingTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        RequestAttributes context = RequestContextHolder.currentRequestAttributes();
        UserRequestContext siteRequestContext = UserRequestContextHolder.getLocalRequestContext();
        return () -> {
            try {
                RequestContextHolder.setRequestAttributes(context);
                UserRequestContextHolder.setUserRequestContext(siteRequestContext);
                runnable.run();
            } finally {
                UserRequestContextHolder.destroyUserRequestContext();
            }
        };
    }
}
